// 工具函数
export const myJSONParse = <T>(value: string, tips: string = ''): T | any => {
  try {
    return JSON.parse(value)
  } catch (error) {
    console.log('JSON解析失败', { value, tips })
  }
}

export const getLocalStorage: getLocalStorageProps = (key: string) => {
  const value = localStorage.getItem(key)
  const IGNORE_ARR = ['token']
  if (IGNORE_ARR.includes(key)) return value
  else {
    if (!value) return null
    return myJSONParse(value, key)
  }
}

export const setLocalStorage: setLocalStorageProps = (key: string, value: any) => {
  if (typeof value === 'string') localStorage.setItem(key, value)
  else localStorage.setItem(key, JSON.stringify(value))
}

export const dateToMs = (date: string | number | Date) => {
  const result = new Date(date).getTime()
  return result
}

// 设置cookie相关

/**
 * 设置cookie
 * @param {string} name - cookie的名称
 * @param {string} value - cookie的值
 * @param {number} expires - cookie的过期时间（单位：毫秒）
 * @param {string} path - cookie的路径
 * @param {string} domain - cookie的域名
 * @param {boolean} secure - 是否使用安全连接设置cookie
 */
export const setCookie = (
  name: string,
  value: string,
  expires: number,
  domain?: string,
  path?: string,
  secure?: boolean
) => {
  let cookieString = name + '=' + encodeURIComponent(value)

  if (expires) {
    let expirationDate = new Date()
    expirationDate.setTime(expirationDate.getTime() + expires * 24 * 60 * 60 * 1000)
    cookieString += '; expires=' + expirationDate.toUTCString()
  }

  if (path) {
    cookieString += '; path=' + path
  }

  if (domain) {
    cookieString += '; domain=' + domain
  }

  if (secure) {
    cookieString += '; secure'
  }

  document.cookie = cookieString
}

/**
 * 获取指定名称的cookie值。
 *
 * @param {string} name - 要获取的cookie的名称。
 * @returns {string | null} - 返回cookie的值，如果不存在则返回null。
 */

export const getCookie = (name: string) => {
  let cookieName = name + '='
  let cookies = document.cookie.split(';')

  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i].trim()

    if (cookie.indexOf(cookieName) === 0) {
      return decodeURIComponent(cookie.substring(cookieName.length))
    }
  }

  return null
}

/**
 * 删除指定名称的cookie
 * @param name cookie的名称
 * @param path cookie的路径
 * @param domain cookie的域名
 */
export const removeCookie = (name: string, path: string, domain: string) => {
  setCookie(name, '', -1, path, domain, false)
}
